package com.itheima.d01_reflect_use;

import java.io.*;
import java.lang.reflect.Field;

public class Test {

    /**
     * 设计方法，保存任意对象的属性名称和属性值到文件中
     */
    public static void saveObject(Object obj) throws Exception {
        try (
                OutputStream fis = new FileOutputStream("day16_reflect_annotation_proxy\\src\\com\\itheima\\d01_reflect_use\\objects.txt", true);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fis));
                ) {
            //1.获取当前对象的Class对象（获取对象的类对象/图纸对象）
            Class<?> aClass = obj.getClass();

            //2.获取当前对象所有声明的属性Field对象
            Field[] declaredFields = aClass.getDeclaredFields();

            //3.遍历属性Field对象，获取属性名称和属性值
            bw.write("======"+aClass.getName() +"======"+ "\r\n");
            for (Field field : declaredFields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object fieldValue = field.get(obj);
                //4.将属性名称和属性值保存到文件中
                bw.write(fieldName + "=" + fieldValue+"\r\n");
                System.out.println(fieldName + "=" + fieldValue);
            }
            bw.write("\r\n");
            bw.write("\r\n");
            bw.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public static void main(String[] args) throws Exception {
        saveObject(new Cat("小猫", 3, 5.5));
        System.out.println("==================================");
        saveObject(new Student("小王", 18, 180.5, "男"));
    }
}
